package com.qianfeng.project.model.callback;

import org.apache.http.Header;

import com.loopj.android.http.AsyncHttpResponseHandler;

//android-async-http开源框架可以是我们轻松的获取网络数据或者向服务器发送数据
public abstract class BaseCallback<T> extends AsyncHttpResponseHandler {

	@SuppressWarnings("rawtypes")
	protected Class clazz;

	@SuppressWarnings("rawtypes")
	protected BaseCallback(Class clazz) {
		this.clazz = clazz;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
		super.onSuccess(statusCode, headers, responseBody);
		T t = null;
		if (responseBody != null && responseBody.length > 0) {
			String json = new String(responseBody);
			t = (T) GsonObjHelper.gson.fromJson(json, clazz);
			onSuccess(statusCode, headers, t);
		} else {
			onSuccess(statusCode, headers, t);
		}
	}

	@Override
	public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
		super.onFailure(statusCode, headers, responseBody, error);
		String msg = "";
		if (responseBody != null && responseBody.length > 0) {
			msg = new String(responseBody);
		} else {
			msg = error.getMessage();
		}
		onFailure(statusCode, headers, msg);
	}

	public abstract void onSuccess(int statusCode, Header[] headers, T t);

	public abstract void onFailure(int statusCode, Header[] headers, String msg);

}
